import React, { useState, useEffect } from 'react';
import { Table, Card, Typography, Image, Tooltip, message, Spin, Button, Space, Alert, Slider, Row, Col } from 'antd';
import { EyeOutlined, CopyOutlined, SettingOutlined } from '@ant-design/icons';
import styled from '@emotion/styled';
import type { ColumnsType, TableRowSelection } from 'antd/es/table';

const { Title, Text } = Typography;

/**
 * 热搜数据项接口定义
 */
interface HotSearchItem {
  id: string;
  content: string;
  src: string;
  translate?: string;
}

/**
 * 热搜数据结构接口
 */
interface HotSearchData {
  content: string[];
  src: string[];
  translate?: string[];
}

/**
 * HotSearch页面组件 - 显示热搜数据表格
 * 功能：根据当前日期查询hot-日期.json文件，展示图片和内容
 */
const HotSearch: React.FC = () => {
  const [data, setData] = useState<HotSearchItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [currentDate, setCurrentDate] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<HotSearchItem[]>([]);
  const [columnsPerRow, setColumnsPerRow] = useState<number>(10); // 每行显示的列数，默认10列

  /**
   * 获取当前日期字符串 (YYYY-MM-DD格式)
   */
  const getCurrentDate = (): string => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  /**
   * 动态加载指定日期的热搜数据
   */
  const loadHotSearchData = async (date: string) => {
    setLoading(true);
    try {
      // 动态导入JSON文件
      const jsonData = await import(`../../mock/hot_search/hot-${date}.json`);
      const hotSearchData: HotSearchData = jsonData.default || jsonData;
      
      // 转换数据格式为表格所需格式
      const tableData: HotSearchItem[] = [];
      const maxLength = Math.max(
        hotSearchData.content?.length || 0,
        hotSearchData.src?.length || 0,
        hotSearchData.translate?.length || 0
      );

      for (let i = 0; i < maxLength; i++) {
        tableData.push({
          id: `item-${i}`,
          content: hotSearchData.content?.[i] || '',
          src: hotSearchData.src?.[i] || '',
          translate: hotSearchData.translate?.[i] || ''
        });
      }

      setData(tableData);
      message.success(`成功加载 ${date} 的热搜数据，共 ${tableData.length} 条`);
    } catch (error) {
      console.error('加载热搜数据失败:', error);
      message.error(`加载 ${date} 的热搜数据失败，请检查文件是否存在`);
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 复制选中内容到剪贴板
   */
  const handleCopySelected = async () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要复制的内容');
      return;
    }

    try {
      const contentText = selectedRows
        .map(item => item.content)
        .filter(content => content)
        .join('\n');
      
      await navigator.clipboard.writeText(contentText);
      message.success(`已复制 ${selectedRows.length} 条内容到剪贴板`);
    } catch (error) {
      message.error('复制失败，请手动复制');
    }
  };

  /**
   * 行选择配置
   */
  const rowSelection: TableRowSelection<HotSearchItem> = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[], newSelectedRows: HotSearchItem[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
      setSelectedRows(newSelectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log('全选状态:', selected, selectedRows, changeRows);
    },
  };

  /**
   * 组件挂载时加载当前日期的数据
   */
  useEffect(() => {
    const today = getCurrentDate();
    setCurrentDate(today);
    loadHotSearchData(today);
  }, []);

  /**
   * 表格列配置 - 优化多列布局
   */
  const columns: ColumnsType<HotSearchItem> = [
    {
      title: '序号',
      key: 'index',
      width: 60,
      align: 'center',
      fixed: 'left',
      render: (_, __, index) => index + 1,
    },
    {
      title: '图片',
      dataIndex: 'src',
      key: 'src',
      width: 100,
      align: 'center',
      render: (src: string) => {
        if (!src) return <Text type="secondary">无图片</Text>;
        
        return (
          <ImageContainer>
            <StyledImage
              src={src}
              alt="热搜图片"
              width={50}
              height={50}
              preview={{
                mask: <EyeOutlined />,
                maskClassName: 'image-preview-mask'
              }}
              fallback=""
            />
          </ImageContainer>
        );
      },
    },
    {
      title: '原文内容',
      dataIndex: 'content',
      key: 'content',
      width: 300,
      ellipsis: {
        showTitle: false,
      },
      render: (content: string) => (
        <Tooltip title={content} placement="topLeft">
          <Text>{content}</Text>
        </Tooltip>
      ),
    },
    {
      title: '翻译内容',
      dataIndex: 'translate',
      key: 'translate',
      width: 300,
      ellipsis: {
        showTitle: false,
      },
      render: (translate: string[]) => {
        const translateText = Array.isArray(translate) ? translate.join(' ') : translate || '暂无翻译';
        return (
          <Tooltip title={translateText} placement="topLeft">
            <Text type="secondary">{translateText}</Text>
          </Tooltip>
        );
      },
    },
  ];

  return (
    <HotSearchContainer>
      <Title level={2}>TikTok 热搜数据表格</Title>
      <Text type="secondary">
        当前显示日期：{currentDate} 的热搜数据（共 {data.length} 条）
      </Text>
      
      {/* 列数配置控件 */}
      <ConfigCard>
        <Row align="middle" gutter={16}>
          <Col>
            <SettingOutlined style={{ fontSize: 16, color: '#1890ff' }} />
          </Col>
          <Col>
            <Text strong>每行显示列数：</Text>
          </Col>
          <Col flex={1}>
             <Slider
               min={1}
               max={10}
               value={columnsPerRow}
               onChange={setColumnsPerRow}
               marks={{
                 1: '1',
                 2: '2',
                 4: '4',
                 6: '6',
                 8: '8',
                 10: '10'
               }}
               style={{ width: 300 }}
             />
           </Col>
          <Col>
            <Text type="secondary">当前：{columnsPerRow}列</Text>
          </Col>
        </Row>
      </ConfigCard>
      
      {/* 批量操作工具栏 */}
      {selectedRowKeys.length > 0 && (
        <Alert
          message={
            <Space>
              <span>已选择 {selectedRowKeys.length} 条数据</span>
              <Button 
                type="primary" 
                size="small" 
                icon={<CopyOutlined />}
                onClick={handleCopySelected}
              >
                复制选中内容
              </Button>
              <Button 
                size="small" 
                onClick={() => {
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                }}
              >
                清空选择
              </Button>
            </Space>
          }
          type="info"
          showIcon
          style={{ marginTop: 16 }}
        />
      )}
      
      {/* 多列卡片布局 */}
      <Spin spinning={loading} tip="加载数据中...">
        <CardsContainer>
          <Row gutter={[16, 16]}>
            {data.map((item, index) => (
              <Col 
                 key={item.id} 
                 span={24 / columnsPerRow}
                 xs={24}
                 sm={columnsPerRow <= 2 ? 24 / columnsPerRow : 12}
                 md={columnsPerRow <= 4 ? 24 / columnsPerRow : 6}
                 lg={columnsPerRow <= 6 ? 24 / columnsPerRow : 4}
                 xl={columnsPerRow <= 8 ? 24 / columnsPerRow : 3}
                 xxl={24 / columnsPerRow}
               >
                <DataCard
                  hoverable
                  size="small"
                  className={selectedRowKeys.includes(item.id) ? 'selected' : ''}
                  onClick={() => {
                    const newSelectedKeys = selectedRowKeys.includes(item.id)
                      ? selectedRowKeys.filter(key => key !== item.id)
                      : [...selectedRowKeys, item.id];
                    const newSelectedRows = data.filter(row => newSelectedKeys.includes(row.id));
                    setSelectedRowKeys(newSelectedKeys);
                    setSelectedRows(newSelectedRows);
                  }}
                >
                  <CardHeader>
                    <Text strong>#{index + 1}</Text>
                    {selectedRowKeys.includes(item.id) && (
                      <SelectedIcon>✓</SelectedIcon>
                    )}
                  </CardHeader>
                  
                  {item.src && (
                     <ImageSection>
                       <StyledImage
                         src={item.src}
                         alt="热搜图片"
                         width="100%"
                         height={80}
                         preview={{
                           mask: <EyeOutlined />,
                         }}
                         fallback=""
                       />
                     </ImageSection>
                   )}
                  
                  <ContentSection>
                    <ContentTitle>原文内容</ContentTitle>
                    <Tooltip title={item.content}>
                      <ContentText>{item.content || '无内容'}</ContentText>
                    </Tooltip>
                  </ContentSection>
                  
                  {item.translate && (
                    <ContentSection>
                      <ContentTitle>翻译内容</ContentTitle>
                      <Tooltip title={Array.isArray(item.translate) ? item.translate.join(' ') : item.translate}>
                        <TranslateText>
                          {Array.isArray(item.translate) ? item.translate.join(' ') : item.translate || '暂无翻译'}
                        </TranslateText>
                      </Tooltip>
                    </ContentSection>
                  )}
                </DataCard>
              </Col>
            ))}
          </Row>
        </CardsContainer>
      </Spin>
    </HotSearchContainer>
  );
};

// 样式组件
const HotSearchContainer = styled.div`
  padding: 24px;
  max-width: 1600px;
  margin: 0 auto;
`;

const ConfigCard = styled(Card)`
  margin: 16px 0;
  
  .ant-card-body {
    padding: 16px;
  }
`;

const CardsContainer = styled.div`
  margin-top: 24px;
`;

const DataCard = styled(Card)`
  height: 100%;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }
  
  &.selected {
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  }
  
  .ant-card-body {
    padding: 8px;
  }
`;

const CardHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 4px;
  border-bottom: 1px solid #f0f0f0;
  
  .ant-typography {
    font-size: 12px;
    margin: 0;
  }
`;

const SelectedIcon = styled.span`
  color: #1890ff;
  font-weight: bold;
  font-size: 14px;
`;

const ImageSection = styled.div`
  margin-bottom: 8px;
  
  .ant-image {
    width: 100%;
    border-radius: 4px;
    overflow: hidden;
  }
`;

const ContentSection = styled.div`
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
`;

const ContentTitle = styled.div`
  font-size: 10px;
  color: #666;
  margin-bottom: 2px;
  font-weight: 500;
`;

const ContentText = styled.div`
  font-size: 12px;
  line-height: 1.3;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
`;

const TranslateText = styled.div`
  font-size: 11px;
  line-height: 1.3;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
`;

const StyledImage = styled(Image)`
  border-radius: 6px;
  object-fit: cover;
`;

export default HotSearch;